<template>
  <div class="img-upload-box">
    <div
      @click="bindItemClick(idx,file)"
      class="img-item img"
      v-for="(file,idx) in files"
      :key="idx">
      <layout-icon color="#999" size="40" type="iconfiletext"></layout-icon>
      <div class="file-name" v-if="fileTaskList[idx] && fileTaskList[idx].filename">{{fileTaskList[idx].filename}}</div>
      <!---->
      <span v-if="fileTaskList[idx] && fileTaskList[idx].task_progress>0 &&  fileTaskList[idx].task_progress<100" class="progress" >{{fileTaskList[idx].task_progress}}%</span>
    </div>
    <div
      class="img-item add"
      @click="addFn"
      v-if="!readonly && files.length<limit"
    >
      <layout-icon color="#ddd" size="40" type="iconplus"></layout-icon>
    </div>
  </div>

</template>
<script>

import { chooseFileByPromise, chooseImageByPromise, getArrColumn, getDomain, uploadImages, createUpTaskArr } from '@/common/helper'
import { Exception } from '@/common/Exception'
import LayoutIcon from '@/componets/layout-icon/layout-icon'
export default {
  components: { LayoutIcon },
  mixins: [],
  props: {
    extension: {
      type: Array,
      default: () => ['doc', 'docx', 'xls', 'xlsx', 'pdf']
    },
    readonly: {
      type: Boolean,
      default: false
    },
    // 额外参数，可以带回去
    ext: {
      default: false
    },
    limit: {
      default: 9,
      type: Number
    },
    has: {
      default: () => []
    }
  },
  data () {
    return {
      fileTaskList: [],
      clickStatus: false,
      tempList: [],
      cate_ids: '',
      files: []
    }
  },
  watch: {
    fileTaskList:{
      deep: true,
      immediate: true,
      handler(newVal) {
        console.log(newVal)
      }
    },
    has: {
      deep: true,
      immediate: true,
      handler (newVal) {
        console.log(newVal)
        if (Array.isArray(newVal) && newVal.length > 0) {
          this.files = newVal.concat([])
          console.log(this.files)
        }
      }
    }
  },
  methods: {
    bindItemClick (idx, img) {
      uni.showActionSheet({
        itemList: ['移除文件'],
        success: (res) => {
          const { tapIndex } = res

          // if (tapIndex === 0) {
          //   uni.previewImage({
          //     urls: [img]
          //   })
          // }
          if (tapIndex === 0) {
            // this.tempList.splice(idx, 1)
            this.files.splice(idx, 1)
            this.fileTaskList.splice(idx, 1)

            this.$emit('done', { files: this.files, ext: this.ext })
          }
        },
        fail (res) {

        }
      })
    },
    handlerPressFunc (res, idx, vm) {
      const { progress, totalBytesSent, totalBytesExpectedToSend } = res
      console.log(`下标${idx}上传进度${progress}`)
      // console.log(`下标${idx}已经上传的数据长度${totalBytesSent}`)
      // console.log(`下标${idx}预期需要上传的数据总长度${totalBytesExpectedToSend}`)
      // console.log(vm)
      const _idx = Number(idx)+this.files.length
      vm.$set(vm.fileTaskList[_idx], 'task_progress', progress)
    },
    async addFn () {
      try {
        var that = this
        if (this.clickStatus) throw Error('操作过快')
        // 已经过滤了用户取消选择的情况
        const localFiles = await chooseFileByPromise({ count: this.limit - this.files.length, extension: this.extension }).catch((errObj) => { throw errObj })

        // name: "全景导览.xlsx"
        // path: "http://tmp/wx3d24c565489e305b.o6zAJs6rxcGwIujkB7cIhatPZD2U.mbw1avdJGbOy46f7e90279a0af397af0f5ab42b5f1b8.xlsx"
        // size: 13263
        // time: 1586493337
        // type: "file"
        const arr1 = localFiles.map(file => {
          return { ...file, task: { progress: 0, totalBytesSent: 0, totalBytesExpectedToSend: 0 } }
        })
        this.tempList = this.tempList.concat(arr1)
        const files = getArrColumn(localFiles, 'path')

        this.fileTaskList = []
        this.fileTaskList = createUpTaskArr(this.files.length + files.length)
        console.log(this.fileTaskList)
        for (var i = 0; i < localFiles.length; i++) {
          this.fileTaskList[(i + this.files.length)].filename = localFiles[i].name
        }
        console.log(files)
        const ossUrls = await uploadImages({ imgs: files, handlerPressFn: this.handlerPressFunc, vmobj: that }).catch(msg => { throw Error(msg) })

        for (var i = 0; i < ossUrls.length; i++) {
          ossUrls[i] = getDomain(ossUrls[i])
        }

        this.files = this.files.concat(ossUrls)
        this.clickStatus = false
        // 把ext带回去，方便弄一些骚操作。比如下标
        this.$emit('done', { files: this.files, ext: this.ext })
      } catch (e) {
        Exception.handle(e)
      }
    }
  }
}
</script>
<style lang="scss">
  .img{
    @include cover-img();
    &-upload-box{
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
    &-item{
      width: 204rpx;
      height: 164rpx;
      margin-bottom: 20rpx;
      margin-right: 20rpx;
      position: relative;
      border-radius: 10rpx;
      overflow: hidden;
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .file-name{
        width: 204rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        margin-top: 6px;
        font-size: 12px;
        color: #999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .progress{
        position: absolute;
        width: 100%;
        height: 100%;
        line-height: 164rpx;
        text-align: center;
        color: white;
        background: rgba(0,0,0,.3);
      }
      &:nth-child(3n+0){
        margin-right: 0;
      }
    }
  }
  .add{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed #ccc;
    box-sizing: border-box;
    margin-right: 0;
    margin-bottom: 0;
  }
</style>
